<template>
  <div>
    我是一个VIS组件
    <div id="canvasDiv"></div>
    <button @click="addNode">增加节点</button>
    <button @click="deleteNode">删除节点</button>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue';
import vis from 'vis';

onMounted(() => {
  createCanvas();
})

// 目标1：创建canvas，点击按钮能够新增节点
// 目标2：节点和节点之间能够连线
// 目标3：能够删除节点，能够删除连线
// 目标4：能够禁止某些类型节点进行连接
// 目标5：理解并节点的一些options配置参数

// 节点数据
let canvasNodes = ref(
  new vis.DataSet([])
)
// 线段数据
let canvasLines = ref(
  new vis.DataSet([])
)
// 显示当前页面有几个节点
let nodeCount = ref(0); 

// 当前点击选中的类型 是node-节点；还是edge-线段
let selectedType = ref(null);
// 当前选中的id
let selectedId = ref(null);
// 线段的起点和终点
let line = reactive({
  from: null,
  to: null,
  fromType: null,
  toType: null
})
// 当前选中节点类型
let selectedResourceType = ref(null);
// 记录连接数组
let linkList = ref([]);

const createCanvas = () => {
  let canvasDiv = document.getElementById('canvasDiv');
  let data = {
    nodes: canvasNodes.value,
    edges: canvasLines.value
  }
  let options = {
    
  }
  let canvasInstance = new vis.Network(canvasDiv, data, options);
  canvasInstance.on('click', (event) => {
    console.log(event, 'event');
    if (event.nodes.length > 0) {
      selectedType.value = 'node';
      selectedId.value = event.nodes[0];
      for (let node in canvasNodes.value._data) {
        if (node.id === event.nodes[0]) {
          selectedResourceType.value = node.type;
        }
      }
      // 如果线段尚未有起点
      if (!line.from) {
        line.from = event.nodes[0];
        line.fromType = selectedResourceType.value;
      } else {
        // 起点和终点不同才允许链接
        if (line.from !== event.nodes[0]) {
          let linkpair = `${line.from}-${event.nodes[0]}`
          // 排除已经连接过的节点
          if (!linkList.value.includes(linkpair)) {
            line.toType = selectedResourceType.value;
            line.to = event.nodes[0];
            canvasLines.value.add(line)
          }
        }
      }
    } else if (event.edges.length > 0) {
      selectedType.value = 'edge';
      selectedId.value = event.edges[0];
    }
  })
}

// 增加节点
const addNode = () => {
  let img_computer = require('@/assets/computer.png');
  let img_computer_selected = require('@/assets/computer_selected.png');
  let newNode = {
    id: ++nodeCount.value,  
    label: '主机',
    type: 'instance',
    shape: 'image',
    image: {
      unselected: img_computer,
      selected: img_computer_selected
    }
  }
  canvasNodes.value.add(newNode);
}
</script>

<style scoped lang="less">
#canvasDiv {
  width: 400px;
  height: 400px;
  background-color: pink;
  margin: 0 auto;
}
</style>